package com.raindrop.rd.util.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件对象信息
 *
 * @author BillDowney
 * @date 2021/3/19 16:28
 */
public class FileInfo extends File {

    /**
     * 按行存文件信息
     */
    private final List<String> lineContent;
    /**
     * 文件的所有内容
     */
    private final StringBuffer content;
    /**
     * 是否读取了文件内容
     */
    private boolean read;

    public FileInfo(String pathname) {
        super(pathname);
        lineContent = new ArrayList<>();
        content = new StringBuffer();
        read = false;
    }

    /**
     * 读取文件内容
     */
    public void readContent() {
        if (!super.exists() || !read) {
            return;
        }
        try (FileReader fileReader = new FileReader(super.getPath());
             BufferedReader br = new BufferedReader(fileReader)) {
            String line;
            while ((line = br.readLine()) != null) {
                lineContent.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            lineContent.clear();
        }
        read = true;
    }

    /**
     * 是否含有文件内容
     *
     * @return true标识content大于0
     */
    public boolean hasContent() {
        return lineContent.size() > 0;
    }

    /**
     * 获取文件内容
     *
     * @return 以列表存每行数据
     */
    public List<String> getLineContent() {
        this.readContent();
        return lineContent;
    }

    public String getContent() {
        this.readContent();
        return content.toString();
    }
}
